#!/usr/bin/env python
# encoding: utf-8
"""
mailer.py

Created by Mike Thorpe on 2009-07-25.
Copyright (c) 2009 Mike Thorpe. All rights reserved.
"""

import sys
import os
import logging

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import mail

from models import FeedItem, Settings

class MainHandler(webapp.RequestHandler):
  def get(self):
    
    self.response.headers["Content-Type"] = "text/plain"

    # Sort by email
    query = Settings.all()

    for user_settings in query:
      wm = WhistleMail(user_settings)
      wm.prepare()
      
      if wm.mail_ready:
        wm.send()
        
      else:
        logging.debug("[mailer] " + "No message for: " + wm.settings.email)


class WhistleMail(object):
  """
  """
  def __init__(self, settings):
    # List of FeedItem entires
    self.matched_articles = []
    # Settings data object
    self.settings = settings
    
    self.msg_body = ""
    self.msg_subject = "[Steam Whistle] News Feed Notification"
    self.mail_ready = False
    
  def prepare(self):
    self.match_articles()
    if self.matched_articles:
      self.create_message()

  def send(self):
    logging.debug("[mailer] Msg Body:\n" + self.msg_body)
    mail.send_mail("steam.whistle.app@gmail.com", self.settings.email, self.msg_subject, self.msg_body)
    
  def create_message(self):
    """
    Create email message for all alerts for a particular 
    email address.
    """
    for article in self.matched_articles:
      self.msg_body += article.title + "\n"
      if article.link:
        self.msg_body += article.link + "\n\n"
      else:
        self.msg_body += "http://www.steampowered.com/" + "\n\n"
    
    self.mail_ready = True
  
  def match_articles(self):
    # Go through articles list looking for matches.
    match_terms = self.settings.commonTerms + self.settings.includedTerms
    excluded_terms = self.settings.excludedTerms

    feed_items = FeedItem.all()
    feed_items.order("-pubDate")
    
    # Match all articles
    ## TODO there's got to be a good way of doing this with zip() or map()
    ##
    for feed_item in feed_items:
      for match_term in match_terms:
        if match_term.lower() in feed_item.title.lower():
          if not feed_item in self.matched_articles:
            self.matched_articles.append(feed_item)

    # Removed exluded terms
    for article in self.matched_articles:
      for term in excluded_terms:
        if term.lower() in article.title.lower():
          self.matched_articles.remove(match)

  
# MAIN WEBAPP
application = webapp.WSGIApplication(
                                     [('/mailer/send', MainHandler)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
